package com.yaorange.guild.common.controller;

import com.yaorange.response.Result;
import com.yaorange.response.enums.ResultCode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

/**
 * @author 15332
 * @version 1.0
 * @date 2025/6/23 19:40
 * @description 文件上传于文件下载控制器
 */
@RestController
@RequestMapping("/common")
public class FileController {
  @Value("${guild.upload}")
  private String upload;

  /**
   * 文件上传
   */
  @PostMapping("/upload")
  public Result uploadFile(@RequestParam("file")MultipartFile file){
    // 判断文件是否是空的
    if (file.isEmpty()){
      return Result.fail(ResultCode.FILE_EMPTY);
    }
    try {
      //创建目标目录
      Path uploadPath = Paths.get(upload);
      if (!Files.exists(uploadPath)){
        Files.createDirectories(uploadPath);
      }
      // 生成唯一的文件名
      String fileName = UUID.randomUUID()+"_"+file.getOriginalFilename();
      Path filePath = uploadPath.resolve(fileName);

      // 保存文件
      Files.copy(file.getInputStream(),filePath);
      return Result.success(fileName);
    }catch (IOException e){
      return Result.fail("文件上传失败");
    }
  }

  /**
   *  文件下载
   */
  @GetMapping("/download/{fileName}")
  public ResponseEntity<Resource> downLoadFile(@PathVariable String fileName){
    try {
      // 构建文件路径
      Path filePath = Paths.get(upload).resolve(fileName);
      Resource resource = new FileSystemResource(filePath.toFile());

      if (!resource.exists()||!resource.isReadable()){
        return ResponseEntity.notFound().build();
      }
      return ResponseEntity.ok()
        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
        .body(resource);
    }catch (Exception e){
      return ResponseEntity.status(500).body(null);
    }
  }
}
